<?php

namespace App\Http\Controllers\Common;

use App\Common\ImageUploadCommon;
use App\Http\Controllers\Controller;
use App\Service\WeChatService;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;

class CommonController extends Controller
{
    public $upload;
    public $weChatService;
    public function __construct(
        ImageUploadCommon $upload,
        WeChatService $weChatService
    ){
        $this->upload = $upload;
        $this->weChatService = $weChatService;
    }

    /**
     * 图片上传
     * @param Request $request
     */
    public function uploadImg(Request $request) {
        try {
            $path = $this->upload->save($request->img, 'images', 'img', '');
        } catch (\Exception $exception) {
            return response($exception->getMessage());
        }
        return response($path);
    }

    /**
     * 获取accessToken
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function getAccessToken() {
        try {
            $accessToken = $this->weChatService->getAccessToken();
        } catch (\Exception $exception) {
            return response($exception->getMessage());
        }
        return response($accessToken);
    }

    /**
     * 将用户微信信息存入session
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function setUserWeChatInfo(Request $request) {
        try {
            $userWeChatInfo = $this->weChatService->setWeChatUserInfo(request(['openid', 'avatar', 'nickname']));
        } catch (\Exception $exception) {
            return response($exception->getMessage());
        }
        return response($userWeChatInfo);
    }

}
